{% extends "members/base.html" %}

{% block title %}发布量表{% endblock %}

{% block extra_css %}
<style>
.scale-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.scale-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}

.scale-card.selected {
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.scale-meta {
    font-size: 0.875rem;
    color: #6c757d;
}

.scale-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.25rem;
    margin-top: 0.5rem;
}

.scale-tag {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 12px;
    color: #495057;
}

.publish-form {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 1.5rem;
    margin-top: 2rem;
}

.preview-section {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1rem;
}

.filter-section {
    background: white;
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.category-filter {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 0.5rem;
}

.category-btn {
    padding: 0.375rem 0.75rem;
    border: 1px solid #dee2e6;
    background: white;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.875rem;
}

.category-btn:hover {
    background: #e9ecef;
}

.category-btn.active {
    background: #007bff;
    color: white;
    border-color: #007bff;
}

.published-indicator {
    position: absolute;
    top: 10px;
    right: 10px;
    background: #28a745;
    color: white;
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    font-size: 0.75rem;
}

@media (max-width: 768px) {
    .category-filter {
        justify-content: center;
    }
    
    .scale-card {
        margin-bottom: 1rem;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="bi bi-broadcast me-2"></i>发布量表</h2>
            <p class="text-muted mb-0">选择系统内置量表进行发布，生成独有的访问链接</p>
        </div>
        <a href="{{ url_for('members.scale_publications') }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i>返回发布管理
        </a>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label">搜索量表</label>
                <div class="input-group">
                    <input type="text" class="form-control" id="search-input" placeholder="输入量表名称或关键词...">
                    <button class="btn btn-outline-secondary" onclick="searchScales()">
                        <i class="bi bi-search"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <label class="form-label">排序方式</label>
                <select class="form-select" id="sort-by" onchange="loadScales()">
                    <option value="title">按名称排序</option>
                    <option value="usage_count">按使用量排序</option>
                    <option value="created_at">按创建时间排序</option>
                </select>
            </div>
            <div class="col-md-3 mb-3">
                <label class="form-label">显示方式</label>
                <select class="form-select" id="show-published" onchange="loadScales()">
                    <option value="all">显示全部</option>
                    <option value="unpublished">仅未发布</option>
                    <option value="published">仅已发布</option>
                </select>
            </div>
        </div>
        
        <div class="mb-3">
            <label class="form-label">量表分类</label>
            <div class="category-filter" id="category-filter">
                <button class="category-btn active" data-category="" onclick="selectCategory(this, '')">
                    全部分类
                </button>
                <!-- 分类按钮将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <!-- 量表列表 -->
    <div class="row" id="scales-container">
        <!-- 量表卡片将通过JavaScript动态加载 -->
    </div>

    <!-- 分页 -->
    <nav aria-label="分页导航" id="pagination-container" class="mt-4">
        <!-- 分页将通过JavaScript动态生成 -->
    </nav>

    <!-- 发布表单 -->
    <div class="publish-form d-none" id="publish-form">
        <h5><i class="bi bi-gear me-2"></i>发布设置</h5>
        <p class="text-muted">为选中的量表配置发布信息</p>
        
        <form id="publication-form">
            <input type="hidden" id="selected-scale-id">
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">自定义标题 <span class="text-muted">(可选)</span></label>
                    <input type="text" class="form-control" id="custom-title" maxlength="200" 
                           placeholder="留空则使用原量表标题">
                    <div class="form-text">自定义标题将显示在公开访问页面</div>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label class="form-label">发布状态</label>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="is-active" checked>
                        <label class="form-check-label" for="is-active">
                            立即启用发布
                        </label>
                    </div>
                    <div class="form-text">关闭后，生成的链接将无法访问</div>
                </div>
            </div>
            
            <div class="mb-3">
                <label class="form-label">自定义描述 <span class="text-muted">(可选)</span></label>
                <textarea class="form-control" id="custom-description" rows="3" maxlength="500" 
                          placeholder="留空则使用原量表描述"></textarea>
                <div class="form-text">自定义描述将显示在公开访问页面，帮助用户了解测评目的</div>
            </div>
            
            <!-- 预览区域 -->
            <div class="preview-section">
                <h6><i class="bi bi-eye me-2"></i>发布预览</h6>
                <div id="preview-content">
                    <p class="text-muted">请先选择要发布的量表</p>
                </div>
            </div>
            
            <div class="text-end mt-3">
                <button type="button" class="btn btn-secondary me-2" onclick="cancelPublish()">
                    <i class="bi bi-x-circle me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary" onclick="publishScale()">
                    <i class="bi bi-broadcast me-1"></i>确认发布
                </button>
            </div>
        </form>
    </div>

    <!-- 加载状态 -->
    <div class="text-center py-5" id="loading-indicator">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2 text-muted">正在加载量表列表...</p>
    </div>

    <!-- 空状态 -->
    <div class="text-center py-5 d-none" id="empty-state">
        <i class="bi bi-inbox display-1 text-muted"></i>
        <h4 class="mt-3 text-muted">暂无可发布的量表</h4>
        <p class="text-muted">当前筛选条件下没有找到可发布的系统内置量表</p>
    </div>
</div>

<!-- 发布成功模态框 -->
<div class="modal fade" id="successModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="bi bi-check-circle me-2"></i>发布成功
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <i class="bi bi-broadcast display-4 text-success"></i>
                </div>
                <h6>量表已成功发布！</h6>
                <p class="text-muted mb-3">您的量表已生成独有的访问链接，可以分享给他人进行测评。</p>
                
                <div class="mb-3">
                    <label class="form-label">公开访问链接</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="success-public-url" readonly>
                        <button class="btn btn-outline-secondary" onclick="copySuccessLink()">
                            <i class="bi bi-clipboard"></i> 复制
                        </button>
                    </div>
                </div>
                
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>提示：</strong>您可以在"发布管理"页面查看和管理所有发布的量表。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a href="{{ url_for('members.scale_publications') }}" class="btn btn-primary">
                    <i class="bi bi-list-ul me-1"></i>查看发布管理
                </a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentPage = 1;
let totalPages = 1;
let selectedScaleId = null;
let publishedScales = new Set(); // 存储已发布的量表ID
const perPage = 12;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
    loadScales();
    loadPublishedScales();
});

// 加载分类
function loadCategories() {
    apiRequest('/api/scales/categories')
        .then(response => {
            if (response.code === 200) {
                displayCategories(response.data);
            }
        })
        .catch(error => {
            console.error('加载分类失败:', error);
        });
}

// 显示分类
function displayCategories(categories) {
    const container = document.getElementById('category-filter');
    const existingButtons = container.innerHTML;
    
    const categoryButtons = categories.map(cat => `
        <button class="category-btn" data-category="${cat.id}" onclick="selectCategory(this, ${cat.id})">
            ${cat.name}
        </button>
    `).join('');
    
    container.innerHTML = existingButtons + categoryButtons;
}

// 选择分类
function selectCategory(button, categoryId) {
    // 移除所有active类
    document.querySelectorAll('.category-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 添加active类到当前按钮
    button.classList.add('active');
    
    // 重新加载量表
    loadScales(1, categoryId);
}

// 加载已发布的量表
function loadPublishedScales() {
    apiRequest('/api/scales/my-publications?per_page=1000')
        .then(response => {
            if (response.code === 200) {
                publishedScales.clear();
                response.data.publications.forEach(pub => {
                    publishedScales.add(pub.scale.id);
                });
                // 重新渲染量表列表以显示发布状态
                if (document.getElementById('scales-container').children.length > 0) {
                    loadScales(currentPage);
                }
            }
        })
        .catch(error => {
            console.error('加载已发布量表失败:', error);
        });
}

// 加载量表列表
function loadScales(page = 1, categoryId = null) {
    currentPage = page;
    
    // 显示加载状态
    document.getElementById('loading-indicator').style.display = 'block';
    document.getElementById('scales-container').innerHTML = '';
    document.getElementById('pagination-container').innerHTML = '';
    document.getElementById('empty-state').classList.add('d-none');
    
    // 构建查询参数
    const params = new URLSearchParams({
        page: page,
        per_page: perPage,
        is_system: 'true' // 只获取系统内置量表
    });
    
    // 添加筛选参数
    if (categoryId !== null && categoryId !== '') {
        params.append('category_id', categoryId);
    }
    
    const searchInput = document.getElementById('search-input').value;
    const sortBy = document.getElementById('sort-by').value;
    const showPublished = document.getElementById('show-published').value;
    
    if (searchInput) params.append('search', searchInput);
    if (sortBy) params.append('sort_by', sortBy);
    
    apiRequest(`/api/scales?${params.toString()}`)
        .then(response => {
            if (response.code === 200) {
                let scales = response.data.scales;
                
                // 根据发布状态筛选
                if (showPublished === 'published') {
                    scales = scales.filter(scale => publishedScales.has(scale.id));
                } else if (showPublished === 'unpublished') {
                    scales = scales.filter(scale => !publishedScales.has(scale.id));
                }
                
                displayScales(scales);
                updatePagination(response.data.pagination);
            } else {
                throw new Error(response.message || '加载失败');
            }
        })
        .catch(error => {
            console.error('加载量表列表失败:', error);
            showResult(false, '加载量表列表失败: ' + error.message);
        })
        .finally(() => {
            document.getElementById('loading-indicator').style.display = 'none';
        });
}

// 显示量表列表
function displayScales(scales) {
    const container = document.getElementById('scales-container');
    
    if (scales.length === 0) {
        document.getElementById('empty-state').classList.remove('d-none');
        return;
    }
    
    container.innerHTML = scales.map(scale => `
        <div class="col-lg-6 col-xl-4 mb-4">
            <div class="card scale-card h-100" onclick="selectScale(${scale.id})" data-scale-id="${scale.id}">
                ${publishedScales.has(scale.id) ? '<div class="published-indicator">已发布</div>' : ''}
                <div class="card-body">
                    <h6 class="card-title">${scale.title}</h6>
                    <p class="card-text text-muted small">
                        ${scale.description ? 
                            (scale.description.length > 100 ? 
                                scale.description.substring(0, 100) + '...' : 
                                scale.description) : 
                            '暂无描述'}
                    </p>
                    
                    <div class="scale-meta mb-2">
                        <span><i class="bi bi-question-circle me-1"></i>${scale.question_count || 0} 题</span>
                        <span class="ms-3"><i class="bi bi-clock me-1"></i>${scale.estimated_time || 5} 分钟</span>
                        <span class="ms-3"><i class="bi bi-people me-1"></i>${scale.usage_count || 0} 次使用</span>
                    </div>
                    
                    ${scale.tags && scale.tags.length > 0 ? `
                        <div class="scale-tags">
                            ${scale.tags.map(tag => `<span class="scale-tag">${tag.name}</span>`).join('')}
                        </div>
                    ` : ''}
                </div>
                
                <div class="card-footer bg-transparent">
                    <small class="text-muted">
                        <i class="bi bi-folder me-1"></i>${scale.category ? scale.category.name : '未分类'}
                        ${scale.is_free ? 
                            '<span class="badge bg-success ms-2">免费</span>' : 
                            `<span class="badge bg-warning ms-2">¥${scale.price || 0}</span>`}
                    </small>
                </div>
            </div>
        </div>
    `).join('');
}

// 选择量表
function selectScale(scaleId) {
    // 检查是否已发布
    if (publishedScales.has(scaleId)) {
        alert('该量表已经发布过了，每个量表只能发布一次。');
        return;
    }
    
    selectedScaleId = scaleId;
    
    // 更新选中状态
    document.querySelectorAll('.scale-card').forEach(card => {
        card.classList.remove('selected');
    });
    document.querySelector(`[data-scale-id="${scaleId}"]`).classList.add('selected');
    
    // 显示发布表单
    document.getElementById('publish-form').classList.remove('d-none');
    document.getElementById('selected-scale-id').value = scaleId;
    
    // 获取量表详情并更新预览
    updatePreview(scaleId);
    
    // 滚动到发布表单
    document.getElementById('publish-form').scrollIntoView({ behavior: 'smooth' });
}

// 更新预览
function updatePreview(scaleId) {
    apiRequest(`/api/scales/${scaleId}`)
        .then(response => {
            if (response.code === 200) {
                const scale = response.data;
                const customTitle = document.getElementById('custom-title').value.trim();
                const customDescription = document.getElementById('custom-description').value.trim();
                
                const previewHtml = `
                    <div class="border rounded p-3">
                        <h6 class="mb-2">${customTitle || scale.title}</h6>
                        <p class="text-muted small mb-2">
                            ${customDescription || scale.description || '暂无描述'}
                        </p>
                        <div class="small text-muted">
                            <span><i class="bi bi-question-circle me-1"></i>${scale.question_count || 0} 题</span>
                            <span class="ms-3"><i class="bi bi-clock me-1"></i>预计 ${scale.estimated_time || 5} 分钟</span>
                        </div>
                        <div class="mt-2">
                            <span class="badge bg-primary">系统内置</span>
                            ${scale.is_free ? 
                                '<span class="badge bg-success ms-1">免费</span>' : 
                                `<span class="badge bg-warning ms-1">¥${scale.price || 0}</span>`}
                        </div>
                    </div>
                `;
                
                document.getElementById('preview-content').innerHTML = previewHtml;
            }
        })
        .catch(error => {
            console.error('获取量表详情失败:', error);
        });
}

// 发布量表
function publishScale() {
    if (!selectedScaleId) {
        alert('请先选择要发布的量表');
        return;
    }
    
    const customTitle = document.getElementById('custom-title').value.trim();
    const customDescription = document.getElementById('custom-description').value.trim();
    const isActive = document.getElementById('is-active').checked;
    
    const data = {
        scale_id: selectedScaleId,
        custom_title: customTitle || null,
        custom_description: customDescription || null,
        is_active: isActive
    };
    
    // 显示加载状态
    const publishBtn = document.querySelector('#publish-form button[onclick="publishScale()"]');
    const originalText = publishBtn.innerHTML;
    publishBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>发布中...';
    publishBtn.disabled = true;
    
    apiRequest('/api/members/scale-publications', {
        method: 'POST',
        body: JSON.stringify(data)
    })
    .then(response => {
        if (response.code === 200) {
            // 显示成功模态框
            document.getElementById('success-public-url').value = response.data.public_url;
            const modal = new bootstrap.Modal(document.getElementById('successModal'));
            modal.show();
            
            // 重置表单
            cancelPublish();
            
            // 更新已发布列表
            publishedScales.add(selectedScaleId);
            
            // 重新加载量表列表以更新发布状态
            loadScales(currentPage);
        } else {
            throw new Error(response.message || '发布失败');
        }
    })
    .catch(error => {
        console.error('发布量表失败:', error);
        showResult(false, '发布失败: ' + error.message);
    })
    .finally(() => {
        publishBtn.innerHTML = originalText;
        publishBtn.disabled = false;
    });
}

// 取消发布
function cancelPublish() {
    selectedScaleId = null;
    document.getElementById('publish-form').classList.add('d-none');
    document.getElementById('custom-title').value = '';
    document.getElementById('custom-description').value = '';
    document.getElementById('is-active').checked = true;
    
    // 移除选中状态
    document.querySelectorAll('.scale-card').forEach(card => {
        card.classList.remove('selected');
    });
}

// 搜索量表
function searchScales() {
    loadScales(1);
}

// 复制成功链接
function copySuccessLink() {
    const url = document.getElementById('success-public-url').value;
    navigator.clipboard.writeText(url).then(() => {
        alert('链接已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
        // 降级方案
        const textArea = document.createElement('textarea');
        textArea.value = url;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        alert('链接已复制到剪贴板');
    });
}

// 更新分页
function updatePagination(pagination) {
    totalPages = pagination.pages;
    const container = document.getElementById('pagination-container');
    
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let paginationHtml = '<ul class="pagination justify-content-center">';
    
    // 上一页
    paginationHtml += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadScales(${currentPage - 1})">
                <i class="bi bi-chevron-left"></i>
            </a>
        </li>
    `;
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            paginationHtml += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="loadScales(${i})">${i}</a>
                </li>
            `;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            paginationHtml += '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }
    
    // 下一页
    paginationHtml += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadScales(${currentPage + 1})">
                <i class="bi bi-chevron-right"></i>
            </a>
        </li>
    `;
    
    paginationHtml += '</ul>';
    container.innerHTML = paginationHtml;
}

// 监听自定义标题和描述的变化，实时更新预览
document.getElementById('custom-title').addEventListener('input', function() {
    if (selectedScaleId) {
        updatePreview(selectedScaleId);
    }
});

document.getElementById('custom-description').addEventListener('input', function() {
    if (selectedScaleId) {
        updatePreview(selectedScaleId);
    }
});

// 搜索框回车事件
document.getElementById('search-input').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        searchScales();
    }
});
</script>
{% endblock %}